<?php

class Maillist_Model_PostsMapper{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable(){
        if (null === $this->_dbTable)
            $this->setDbTable('Maillist_Model_DbTable_Posts');
        return $this->_dbTable;
    }
    
    public function fetchPost4Sending($limit){
        $r = $this->getDbTable()->fetchRow('Publish=1 AND Date >= DATE( NOW( ) )','Date');
        $t1 = $this->getDbTable();
        $t2 = new Maillist_Model_DbTable_Subscribers();
        $t3 = new Maillist_Model_DbTable_SubscribersPosts();
        $sql = $t1->select()->setIntegrityCheck(false)
                ->from(array('p'=>$t1->info(Zend_Db_Table_Abstract::NAME)), array("PostId"=>"Id","Subject", "Text"))
                ->join(array('s'=>$t2->info(Zend_Db_Table_Abstract::NAME)),"p.Date>=s.JoinDate", array("SubscriberId"=>"Id","Email","Name1","Name2","Name3"))
                ->joinLeft(array('sp'=>$t3->info(Zend_Db_Table_Abstract::NAME)),"p.Id=sp.PostId AND s.Id=sp.SubscriberId","")
                ->where('s.Active=1 AND p.Publish=1 AND sp.Id IS NULL')
                ->order('p.Date')
                ->limit($limit,0);
                /*
                    SELECT p.Id,p.Date, s.Id,s.Name1, sp.Id

                    FROM sr_maillist_posts AS p INNER JOIN sr_maillist_subscribers AS s 
                    ON p.Date>=s.JoinDate

                    LEFT JOIN sr_maillist_subscribers_posts AS sp
                    ON p.Id=sp.PostId AND s.Id=sp.SubscriberId

                    WHERE s.Active=1 AND p.Publish=1 AND sp.Id IS NULL

                    ORDER BY p.Date
                */
        $set = $t1->fetchAll($sql);
        $result=array();
        foreach($set as $row){
            $post = new Maillist_Model_Post(
                    array(
                        'Id'=>$row->PostId,
                        'Subject'=>$row->Subject,
                        'Text'=>$row->Text,
                    ));
            $subscriber = new Maillist_Model_Subscriber(
                    array(
                        'Id'=>$row->SubscriberId,
                        'Email'=>$row->Email,
                        'Name1'=>$row->Name1,
                        'Name2'=>$row->Name2,
                        'Name3'=>$row->Name3
                    ));
            $result[] = array($post,$subscriber);
        }
        return  $result;
    }
	
	public function fetchAll($query=null,$start=-1,$limit=-1){
		$t = $this->getDbTable();
        $s = $t->select()->order("Id DESC");
        if ((-1!=$start) && (-1!=$limit))
            $s->limit($limit,$start);
        if (null!=$query) $s->where(new Zend_Db_Expr("Name LIKE '%".$query."%'") );
		return $t->fetchAll( $s)->toArray();
	}
    /*
     * Возвращает категории которые содержат товары
     */
    /*public function fetchNotEmpty($query=null,$start=null,$limit=null){
        $t1 = $this->getDbTable();
        $t2 = new Yamarket_Model_DbTable_Offers();
        $set = $t1->fetchAll($t1->select()->distinct()->setIntegrityCheck(false)
                            ->from(array('t1'=>$t1->info(Zend_Db_Table_Abstract::NAME)))
                            ->join(array('t2'=>$t2->info(Zend_Db_Table_Abstract::NAME)),' t1.Id = t2.CategoryId', null)
                            ->where('t2.Publish = 1'));
        $result=array();
        foreach($set as $row){
            $r = $row->toArray();
            $result[] = new Yamarket_Model_Category($r);
        }
        
        return $result;
	}*/
    
    public function count(){
        $t = $this->getDbTable();
        $a=$t->fetchRow($t->select()->from($t,new Zend_Db_Expr("COUNT(Id) as C")))->toArray();
        return $a['C'];
    }
    
    public function save($params){
        $t = $this->getDbTable();
        if (isset($params['Id']))
            $t->update($params,array('Id=?'=>$params['Id']));
        else
            return $t->insert($params);
        return $params['Id'];
    }
    
    public function delete($id){
        $this->getDbTable()->delete(array('Id=?'=>$id));
    }
}
?>